package com.telecom.sxint.app.core.service.impl.Engineerserviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.zjtele.pubinfo.boot.redis.config.RedisHelper;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.telecom.sxint.app.core.domain.entity.Engineerpojo.App1Employeehours;
import com.telecom.sxint.app.core.domain.entity.Engineerpojo.App1Engineercertification;
import com.telecom.sxint.app.core.domain.entity.Query.PageData;
import com.telecom.sxint.app.core.domain.entity.Vatinvoicepojo.App1Vatinvoinceprintlog;
import com.telecom.sxint.app.core.domain.entity.dto.CertificationQueryDTO;
import com.telecom.sxint.app.core.domain.entity.dto.HoursQueryDTO;
import com.telecom.sxint.app.core.domain.entity.dto.InvoiceFilterDTO;
import com.telecom.sxint.app.core.mapper.Engineermapper.App1EmployeehoursMapper;
import com.telecom.sxint.app.core.service.Engineerservice.IApp1EmployeehoursService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2024-08-19
 */
@Service
public class App1EmployeehoursServiceImpl extends ServiceImpl<App1EmployeehoursMapper, App1Employeehours> implements IApp1EmployeehoursService {
    @Autowired
    private App1EmployeehoursMapper app1EmployeehoursMapper;
    @Autowired
    private RedisHelper redisHelper;

    /**
     * 修改工时
     * @param app1Employeehours
     * @return
     */
    @Override
    public App1Employeehours updateByEmployeeId(App1Employeehours app1Employeehours) {
        // 获取缓存键
        String cacheKey = "employee_hours:" + app1Employeehours.getId();

        // 从Redis中获取缓存数据
        App1Employeehours cachedData = (App1Employeehours) redisHelper.valueGet(cacheKey);
        if (cachedData != null) {
            //删除缓存
            redisHelper.delete(cacheKey);
        }

        // 更新数据库记录
        UpdateWrapper<App1Employeehours> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", app1Employeehours.getId());
        app1EmployeehoursMapper.update(app1Employeehours, updateWrapper);

        // 查询更新后的记录并返回
        QueryWrapper<App1Employeehours> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", app1Employeehours.getId());
        App1Employeehours updatedLog = app1EmployeehoursMapper.selectOne(queryWrapper);
        // 更新缓存
        redisHelper.valueSet(cacheKey, updatedLog,3600L, TimeUnit.SECONDS);
        return updatedLog;
    }
    /**
     *  根据id查询该员工每月信息
     */
    @Override
    public List<App1Employeehours> queryAllById(String id) {
        // 定义缓存的键
        String cacheKey = "employee_hours_monthly_info_employee_id:" + id;

        // 从Redis中获取缓存数据
        List<App1Employeehours> cachedData = (List<App1Employeehours>) redisHelper.valueGet(cacheKey);
        if (cachedData != null) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }

        // 缓存未命中，查询数据库
        QueryWrapper<App1Employeehours> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_id", id);
        queryWrapper.eq("is_delete", 0);
        List<App1Employeehours> resultList = app1EmployeehoursMapper.selectList(queryWrapper);
        // 将查询结果存储到Redis缓存中，设置过期时间为1小时（3600秒）
        redisHelper.valueSet(cacheKey, resultList, 3600L, TimeUnit.SECONDS);

        return resultList; // 返回数据库查询结果
    }
    /**
     * 查询所有工时数据
     * @return
     */
    @Override
    public List<App1Employeehours> listAll() {
        // 定义缓存的键
        String cacheKey = "employee_hours_all";

        // 从Redis中获取缓存数据
        List<App1Employeehours> cachedData = (List<App1Employeehours>) redisHelper.valueGet(cacheKey);
        if (cachedData != null) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        // 缓存未命中，查询数据库
        QueryWrapper<App1Employeehours> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0); // 确保不查询 is_delete 字段为 1 的记录
        List<App1Employeehours> resultList = app1EmployeehoursMapper.selectList(queryWrapper);
        // 将查询结果存储到Redis缓存中，设置过期时间为1小时（3600秒）
        redisHelper.valueSet(cacheKey, resultList, 3600L, TimeUnit.SECONDS);

        return resultList; // 返回数据库查询结果
    }

    /**
     * 根据姓名或人员编码查询研发人员明细和工时
     * @param filter
     * @return
     */
    @Override
    public List<App1Employeehours> queryByEmployeeNameOrId(App1Employeehours filter) {
        // 定义缓存的键
        String cacheKey = "employee_hours_by_name_or_employee_id:" + filter.getEmployeeName() + ":" + filter.getEmployeeId();

        // 从Redis中获取缓存数据
        List<App1Employeehours> cachedData = (List<App1Employeehours>) redisHelper.valueGet(cacheKey);
        if (cachedData != null) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        // 缓存未命中，查询数据库
        QueryWrapper<App1Employeehours> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0); // 确保不查询 is_delete 字段为 1 的记录
        if (filter.getEmployeeName() != null && !filter.getEmployeeName().isEmpty()) {
            queryWrapper.eq("employee_name", filter.getEmployeeName());
        }
        if (filter.getEmployeeId() != null && !filter.getEmployeeId().isEmpty()) {
            queryWrapper.eq("employee_id", filter.getEmployeeId());
        }
        List<App1Employeehours> resultList = app1EmployeehoursMapper.selectList(queryWrapper);
        // 将查询结果存储到Redis缓存中，设置过期时间为1小时（3600秒）
        redisHelper.valueSet(cacheKey, resultList, 3600L, TimeUnit.SECONDS);

        return resultList; // 返回数据库查询结果
    }

    /**
     * 工时分页查询
     * @param hoursQueryDTO
     * @return
     */
    @Override
    public PageData queryHoursPage(HoursQueryDTO hoursQueryDTO) {
//
//        String cacheKey = "employee_hours_page:" + hoursQueryDTO.getCurrentPage() + ":" + hoursQueryDTO.getPageSize();
//
//        // 从Redis中获取缓存数据
//        PageData<App1Employeehours> cachedData = (PageData<App1Employeehours>) redisHelper.valueGet(cacheKey);
//        if (cachedData != null) {
//            // 缓存命中，直接返回缓存数据
//            return cachedData;
//        }
        //1构建查询条件
        Page<App1Employeehours> page = Page.of(hoursQueryDTO.getCurrentPage(), hoursQueryDTO.getPageSize());
        //排序  page.addOrder(new OrderItem(ticketQueryDTO.))
        //2分页查询
        Page<App1Employeehours> p = lambdaQuery()
                .eq(App1Employeehours::getIsDelete, 0) // 确保只查询 is_delete 字段为 0 的记录
                .page(page);
        //3封装VO结果
        PageData<App1Employeehours> dto = new PageData<>();
        //总条数
        dto.setTotal(p.getTotal());
        //当前页
        dto.setCurrentPage(p.getCurrent());
        dto.setPageSize(p.getSize());
        //当前页数条数
        dto.setRecords(p.getRecords());
//        redisHelper.valueSet(cacheKey, dto, 3600L, TimeUnit.SECONDS);
        //4返回
        return dto;
    }

    @Override
    public ResponseData handleSingleUpload(App1Employeehours app1Employeehours) {
        String month = app1Employeehours.getWorkMonth();
        if(StrUtil.isBlank(month)||!month.matches("^(19|20)\\d{2}-(0[1-9]|1[0-2])$")){
            return ResponseData.failed("工时月份不能为空或工时月份格式错误,例：2024-08","410003");
        }
        String engineerId = app1Employeehours.getEmployeeId();
        if(StrUtil.isBlank(engineerId)){
            return ResponseData.failed("工程师id不能为空","410003");
        }
        String engineerName = app1Employeehours.getEmployeeName();
        if(StrUtil.isBlank(engineerName)){
            return ResponseData.failed("工程师姓名不能为空","410003");
        }
        String workHours = app1Employeehours.getWorkMonth();
        if(StrUtil.isBlank(workHours)){
            return ResponseData.failed("工时不能为空","410003");
        }
        app1Employeehours.setId(null);
        app1EmployeehoursMapper.insert(app1Employeehours);
        // 缓存操作
        String cacheKey = "employee_hours:" + app1Employeehours.getEmployeeId() + ":" + month;
        // 缓存插入的数据
        redisHelper.valueSet(cacheKey, app1Employeehours, 3600L, TimeUnit.SECONDS);
        return ResponseData.success("录入成功");
    }

    @Override
    public ResponseData clearData() {
        redisHelper.deletePattern("employee_hours*");

        // 删除数据库中的所有记录
        app1EmployeehoursMapper.delete(null);

        return ResponseData.success("清除成功");
    }

    /**
     * 删除单条数据
     * @param id
     */
    @Override
    public ResponseData DeleteById(Integer id) {

        String cacheKey = "employee_hours:" + id;

        // 删除缓存
        redisHelper.delete(cacheKey);
        UpdateWrapper<App1Employeehours> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id) // 设置更新条件，这里假设id是更新条件
                .set("is_delete", 1); // 设置 is_delete 字段的值为 1
        if (app1EmployeehoursMapper.update(null, updateWrapper) > 0) {
            // 如果更新成功，返回成功响应
            return ResponseData.success("删除成功");
        } else {
            // 如果更新失败，返回失败响应
            return ResponseData.failed("删除失败", "400002");
        }
        // 删除数据库中的记录
//        if(app1EmployeehoursMapper.deleteById(id) == 0){
//            return ResponseData.failed("删除失败","410003");
//        }
    }
    /**
     * 批量删除研究人员信息
     * @param ids
     * @return
     */
    @Override
    public ResponseData deleteBatch(List<Integer> ids) {
        redisHelper.deletePattern("employee_hours*");
        if(CollUtil.isEmpty(ids)){
            return ResponseData.failed("未选择删除记录","410003");
        }
        UpdateWrapper<App1Employeehours> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids) // 设置更新条件，这里假设id是更新条件
                .set("is_delete", 1); // 设置 is_delete 字段的值为 1
        app1EmployeehoursMapper.update(null, updateWrapper);
        return ResponseData.success("删除成功");
    }

    @Override
    public PageData<App1Employeehours> queryByCompanyPage(HoursQueryDTO hoursQueryDTO, String company) {
        Page<App1Employeehours> page = Page.of(hoursQueryDTO.getCurrentPage(), hoursQueryDTO.getPageSize());
        Page<App1Employeehours> result = app1EmployeehoursMapper.selectByCompanyPage(page, company);
        return new PageData<>(result.getRecords(), result.getTotal());
    }
    /**
     * 删除所有数据
     */
    @Override
    public void deleteAll() {
        redisHelper.deletePattern("employee_hours*");
        // 删除数据库中的所有记录
        app1EmployeehoursMapper.delete(null);

    }

}